package com.wss.lsl.test.driven.redis.util;

import java.util.List;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.exceptions.JedisNoScriptException;

/**
 * 加载lua脚本工具
 * 
 * @author Administrator
 *
 */
public class ScriptLoad {

	private String script;

	private String sha1;

	private ScriptLoad() {

	}

	public static ScriptLoad loadScript(String script) {
		ScriptLoad sl = new ScriptLoad();
		sl.script = script;
		
		return sl;
	}

	/**
	 * 执行脚本
	 * 
	 * @param jedis
	 * @param keys
	 * @param args
	 * @param forceEval
	 *            强制执行eval方法
	 * @return
	 */
	public Object execute(Jedis jedis, List<String> keys, List<String> args,
			boolean forceEval) {

		if (forceEval) {
			return jedis.eval(script, keys, args);
		}
		if (sha1 == null) {
			sha1 = jedis.scriptLoad(script);
		}

		Object result = null;
		try {
			result = jedis.evalsha(sha1, keys, args);
		} catch (JedisNoScriptException e) {
			sha1 = jedis.scriptLoad(script);
			result = jedis.evalsha(sha1, keys, args);
		}

		return result;
	}
}
